package com.perfect.service;

import com.perfect.base.BaseService;
import com.perfect.base.ResultInfo;
import com.perfect.dao.ProductMapper;
import com.perfect.dao.UserMapper;
import com.perfect.utils.AssertUtil;
import com.perfect.utils.Md5Util;
import com.perfect.vo.Product;
import com.perfect.vo.Shop;
import com.perfect.vo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@Service
public class UserService extends BaseService<User,Integer> {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ProductMapper productMapper;


    /**
     * 通过用户名获取用户
     * @param username
     * @return
     */
    public User getUser(String username){
        return userMapper.getUserByUserName(username,null);
    }

    /**
     * 用户登录
     * @param username
     * @param pwd
     * @return
     */
    public ResultInfo login(String username,String pwd) {
        ResultInfo resultInfo = new ResultInfo();


        // 参数的非空判断
        if (StringUtils.isBlank(username)&&StringUtils.isBlank(pwd)){
            resultInfo.setCode(0);
            resultInfo.setMsg("用户名密码不能为空！");
            return resultInfo;
        }
        // 如果参数都不为空那就通过username去查询用户记录
        User user = userMapper.getUserByUserName(username,null);
        // 如果查询结果为空表示该用户名不存在
        if(null==user){
            resultInfo.setCode(0);
            resultInfo.setMsg("该用户不存在");
            return resultInfo;
        }

        // 结果不为空就拿传进来的密码和数据库中查到的密码做比较
        // 如果不相等表示密码不正确
        if (!(Md5Util.encode(pwd).equals(user.getPassword()))){
            resultInfo.setCode(0);
            resultInfo.setMsg("用户密码不正确");
            return resultInfo;
        }
        user.setPassword(Md5Util.encode(pwd));
        resultInfo.setResult(user);
        return resultInfo;
    }

    public ResultInfo updatePassword(String id, String oldPwd, String newPwd, String confirmPwd) {
        ResultInfo resultInfo = new ResultInfo();

        User user = userMapper.getUserById(id);
        AssertUtil.isTrue(StringUtils.isBlank(oldPwd),"请输入旧密码");
        AssertUtil.isTrue(!Md5Util.encode(oldPwd).equals(user.getPassword()),"旧密码不正确");
        AssertUtil.isTrue(StringUtils.isBlank(newPwd),"请输入新密码");
        AssertUtil.isTrue(StringUtils.isBlank(confirmPwd),"请确认新密码");

        AssertUtil.isTrue(!newPwd.equals(confirmPwd),"密码不一致，请重新确认密码");
        AssertUtil.isTrue(newPwd.equals(oldPwd),"新密码不能和旧密码一样");

        userMapper.updatePassword(Md5Util.encode(newPwd),id);

        return resultInfo;
    }

    public User getUserById(String id) {
        AssertUtil.isTrue(StringUtils.isBlank(id),"id为空！！！");
        return userMapper.getUserById(id);
    }



    public void uploadImg(HttpServletRequest request) {
        ResultInfo resultInfo = null;

        String id=null;
        Cookie[] cookies = request.getCookies();
        for (Cookie c : cookies){
            if (c.getName().equals("id")){
                id = c.getValue();
                break;
            }
        }

        User user = userMapper.getUserById(id);

        // 获取上传文件的目录
        String uploadFilePath = request.getServletContext().getRealPath("/images/user/");
//        System.out.println("uploadFilePath==="+uploadFilePath);

        // 如果目录不存在则创建
        File uploadFile = new File(uploadFilePath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }

        // 4. 实现上上传文件
        try {
            // 1. 获取Part对象 request.getPart("name"); name代表的是file文件域的name属性值
            // 解析请求的内容提取文件数据
//            @SuppressWarnings("unchecked")
            List<Part> fileParts = (List<Part>) request.getParts();
            // 上传文件
            for (Part filePart : fileParts) {
                String fileName = filePart.getSubmittedFileName();
                if (fileName != null) {
                    String filePath = uploadFilePath + File.separator + fileName;
                    Path path = Paths.get(filePath);
                    Files.copy(filePart.getInputStream(), path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        int row = userMapper.updateByPrimaryKeySelective(user);
        if (row > 0) {
//            resultInfo.setCode(1);
//            request.getSession().setAttribute("user", user);
            System.out.println("更新成功");
        } else {
//            resultInfo.setCode(0);
//            resultInfo.setMsg("更新失败！");
            System.out.println("更新失败");
        }
    }

    public void checkUserName (String username,Integer id){
        User user = userMapper.getUserByUserName(username,id);
        AssertUtil.isTrue(null!=user,"用户名已存在");
    }

    public void saveUser(Integer roleId,User user) {
        checkUserName(user.getUsername(),null);
        user.setRoleId(roleId);
        user.setPassword(Md5Util.encode(user.getPassword()));
        user.setDeleted("0");
        userMapper.insert(user);
    }

    /**
     * 修改用户
     * @param user
     */
    public void updateUser(User user) {
        checkUserName(user.getUsername(),user.getId());
        user.setUpdateDate(new Date());
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void deleteByIds(Integer[] ids) {
        // 判断ids是否为空，长度是否大于0
        AssertUtil.isTrue(ids == null || ids.length == 0, "待删除记录不存在！");
        // 执行删除操作，判断受影响的行数
        AssertUtil.isTrue(userMapper.deleteBatch(ids) != ids.length, "用户删除失败！");
    }

    public Shop getShopByUserId(Integer id) {
        return  userMapper.getShopByUserId(id);
    }


}
